<?php
session_start();
function cURL($url, $header=NULL, $cookie=NULL, $p=NULL)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, $header);
    curl_setopt($ch, CURLOPT_NOBODY, $header);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    if(!strstr($url, 'dialog/oauth')){
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  }
    if ($p) {
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $p);
    }
    $result = curl_exec($ch);
    if ($result) {
      return $result;
    } else {
      return curl_error($ch);
    }
    curl_close($ch);
}
if(isset($_GET['act'])){
  if($_GET['act'] == 'fbauth'){
    if(!empty($_SESSION['user'])){
      echo '1';die;
    }
    $accessToken = $_POST['token'];
    $fbRawResponse = cURL('https://graph.facebook.com/me?access_token='.$accessToken);
    $userInfo = json_decode($fbRawResponse, true);
    if(isset($userInfo['id'])){
      $_SESSION['user'] = $userInfo;
      echo '1';
    }
    else{
      echo '0';
    }
    die;
  }
  elseif($_GET['act'] == 'gplus'){
    echo 'ok';
    // https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=ya29.AHES6ZTqqzy1C0R9H4NYb70aUf-EcXg7YNvtjHZuwmYKlavfLq-iDg
    die;
  }
  elseif($_GET['act'] == 'logout'){
    unset($_SESSION);
  }
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" id="facebook" class="no_js" xmlns:fb="http://ogp.me/ns/fb#" xmlns:og="http://ogp.me/ns#">
<head><meta charset="utf-8" /><title>FB Login API</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head><body>
<script type="text/javascript">
function signinCallback(authResult) {
  if (authResult['access_token']) {
    // Update the app to reflect a signed in user
    // Hide the sign-in button now that the user is authorized, for example:
    $.ajax({
      url: '?act=gplus',
      type: 'POST',
      data: {token: authResult['access_token']},
      success: function(response){
        console.log(response);
      }
    });
    document.getElementById('signinButton').setAttribute('style', 'display: none');
    $('#btnGplusLogout').show();
  } else if (authResult['error']) {
    // Update the app to reflect a signed out user
    // Possible error values:
    //   "user_signed_out" - User is signed-out
    //   "access_denied" - User denied access to your app
    //   "immediate_failed" - Could not automatically log in the user
    console.log('Sign-in state: ' + authResult['error']);
  }
}
function gplusLogout(){
  gapi.auth.signOut();
  document.location.href='?act=logout';
}
function Logout()
{
    FB.logout(function(){document.location.href='?act=logout';});
 
}
function login(){
	FB.login(function(response) {
	  if (response.authResponse) {
	    console.log('Welcome!  Fetching your information.... ');
	    FB.api('/me', function(response) {
	    	console.log(response);
	       	console.log('Good to see you, ' + response.name + '.');
	    });
	  } else {
	    console.log('User cancelled login or did not fully authorize.');
	  }
	}, {scope: 'email', response_type: 'code'});
}
</script>
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    // init the FB JS SDK
    FB.init({
      appId      : '373726459369728',                        // App ID from the app dashboard
      channelUrl : '//fb.com/channel.html', // Channel file for x-domain comms
      status     : true,                                 // Check Facebook Login status
      xfbml      : true                                  // Look for social plugins on the page
    });

    // Additional initialization code such as adding Event Listeners goes here
    FB.Event.subscribe('auth.authResponseChange', function(response)
    {
         if (response.status === 'connected')
         {
            //SUCCESS
            $('#btnLogout').show();
            $('#btnLogin').hide();
            FB.getLoginStatus(function(response) {
              $.ajax({
                url: '?act=fbauth',
                type: 'POST',
                data: {token: response.authResponse.accessToken},
                success: function(response){
                  if(response === '1'){
                    console.log('Session created');
                  }
                  else{
                    console.log('Authentication failed');
                  }
                }
              });
            });
         }  
         else if (response.status === 'not_authorized')
        {
            //FAILED
            console.log('Failed to logout');
            $('#btnLogin').show();
        } else
        {
            //UNKNOWN ERROR. Logged Out
            console.log('Unknown logout error');
        }
    });

  };

  // Load the SDK asynchronously
  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/all.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>
<div>
<span id="signinButton">
  <span
    class="g-signin"
    data-callback="signinCallback"
    data-clientid="992072006437-bh1jb47d6ka5hmdfm3nsj32jmte0d1i6.apps.googleusercontent.com"
    data-cookiepolicy="single_host_origin"
    data-requestvisibleactions="http://schemas.google.com/AddActivity"
    data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile">
  </span>
</span>

<?php if(empty($_SESSION['user'])): ?>
<button id="btnLogin" onClick="login()">Login with Facebook</button>
<?php else: ?>
  <?php echo '<div>Hello, '.$_SESSION['user']['name'].'</div>' ?>
<?php endif; ?>
<button onClick="Logout()" id="btnLogout" style="display:none;">FB Logout</button>
<button onClick="gplusLogout()" id="btnGplusLogout" style="display:none;">Google+ Logout</button>
</div>

<!-- Place this asynchronous JavaScript just before your </body> tag -->
<script type="text/javascript">
  (function() {
   var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
   po.src = 'https://apis.google.com/js/client:plusone.js';
   var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
 })();
</script>
</body>
</html>